//
//  LoanDetailsWebViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/12/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import WebKit

class LoanDetailsWebViewController: KMViewController {

    fileprivate var urlStr = ""
    fileprivate var loanId = "0" //申请id
    
    //需要移除的标签
    var removeElements = [String]()
    var removeIds = [String]()
    
    ///webview
    fileprivate var webView : WKWebView!
    ///进度条
    fileprivate let progressView = UIProgressView()
    
    let config = WKWebViewConfiguration()
    
    init(urlStr:String,title:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.urlStr = webUrl + "/mdaikuandetail/" +  urlStr
        self.title = title
        self.loanId = urlStr
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        
        progressView.trackTintColor = UIColor.clear
        progressView.progressTintColor = UIColor.moveColor()
        self.view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 5))
        }
        
        createWebView()
        
        self.view.bringSubview(toFront: progressView)
    }
    
    deinit {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webView.removeObserver(self, forKeyPath: "title")
    }
    
    fileprivate func createWebView() {
        
        //交互设置
        config.preferences = WKPreferences()
        config.preferences.minimumFontSize = 10
        config.preferences.javaScriptEnabled = true
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        config.userContentController = WKUserContentController()
        config.processPool = WKProcessPool()
        
        self.webView = WKWebView.init(frame: .zero, configuration: config)
        //路径编码
        let string = self.urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        if let url = URL.init(string: string ?? "") {
            let request = URLRequest.init(url: url)
            webView.load(request)
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        self.view.addSubview(webView)
        
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        self.webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if "estimatedProgress" == keyPath {
            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
            if self.progressView.progress == 0 {
                self.progressView.isHidden = false
            }else if self.progressView.progress == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    if self.progressView.progress == 1 {
                        self.progressView.progress = 0
                        self.progressView.isHidden = true
                    }
                }
            }
        }else if "title" == keyPath {
            self.title = webView.title
        }
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
    }
    
}

extension LoanDetailsWebViewController : WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler {
    
    //MARK: 实现js注入方法的协议方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        if message.name == "collectSendKey" {
            
            if let dic = message.body as? [String:Any] {

                let parameters = ["id":dic["id"]!,"money":dic["money"]!,"cycle":dic["cycle"]!,"user_name":KMTool.stringForEnumKey(.phone) ?? "","location":KMTool.stringForEnumKey(.currentCity) ?? ""]

                KMTool.requestGetData(URLString: url_loanRecord, parameters: parameters, success: { (data) in

                }) {

                }
            }
            
            
        }
    }
    
    //MARK: 页面加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
        KMTool.showText(_text: global_requestFailed)
    }
    
    
    
    //MARK: 页面加载成功
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        let removeElement = KMTool.removeHtmlElement(classNames: self.removeElements)
        webView.evaluateJavaScript(removeElement, completionHandler: nil)
        let removeId = KMTool.removeHtmlElementForId(idNames: self.removeIds)
        webView.evaluateJavaScript(removeId, completionHandler: nil)
        KMTool.showText(_text: global_loadSuccess)
        
        //注入js方法
        let js = "function appNumAdd2(){" +
            "var id = " + loanId + ";" +
            "var order_id = " + "0" + ";" +
            "var money = $('.input_money').val();" +
            "var cycle = $(\".zi-blue input[type='hidden']\").val();" +
            "if(cycle == null || cycle == ''){" +
            "cycle = $(\".zi-blue input[type='text']\").val();" +
            "}" + "window.webkit.messageHandlers.collectSendKey.postMessage({id,money,cycle});" + "}";
        self.webView.evaluateJavaScript(js, completionHandler: nil)
        
        config.userContentController.removeScriptMessageHandler(forName: "collectSendKey")
        config.userContentController.add(self, name: "collectSendKey")

    }
    
    //MARK: 拦截网页点击事件
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        let urlString = navigationResponse.response.url?.absoluteString
        
        if urlString! == self.urlStr {
            decisionHandler(.allow)
            return
        }
        
        if !(urlString!.contains("kameng98.com")) && !(urlString!.contains("https://static.bshare.cn/cm.html")) {
            
            //调用js方法
            webView.evaluateJavaScript("appNumAdd2()", completionHandler: nil)
            
            
            let webDetailsVC = WebDetailsViewController.init(urlString: urlString)
            self.navigationController?.pushViewController(webDetailsVC, animated: true)
            
            decisionHandler(.cancel)
            return
        }
        
        if (urlString?.contains(webUrl + "/mdaikuandetail/"))! {
            
            self.loanId = (urlString?.replacingOccurrences(of: webUrl + "/mdaikuandetail/", with: ""))!
        }
        
        
        decisionHandler(.allow)
        
    }
    
    
}
